import React from 'react';
import ReactDOM from 'react-dom';
import { Table, Form, Input, Button ,Select, Row, Col, DatePicker, Icon ,  Message  } from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
const RangePicker = DatePicker.RangePicker;




let Demo = React.createClass({
  contextTypes: {
    router: React.PropTypes.object
  },
  uuid: 0,
  key:  0,
  getInitialState() {
    return {
      loading: false,
      data:[],
      costArry:[], //费用数组
      renderBox:'',
      firstRenderBox:'', //首次进入时预设渲染
      params:[],
      dataList:{},//拼接好的对象
      costType:'decorateCost',
      tenementId:'',
      roomType:'1'//房间类型 1表示房源，2表示房间
    }
  },
  componentDidMount(){
    this.getDecCost();
    let dataList = {};
    dataList.tenementId = this.props.tenementId;
    dataList.costType = this.state.costType;
    dataList.roomType = this.state.roomType;
    this.setState({
      dataList: dataList
    });
  },


  // 获取所有软装项目列表
  getDecCost(){
    Utils.sendAjax({
      url: '/dict/list',
      data:JSON.stringify({"type":"decorateCost"}),
      callback:(result) => {
        if (result.code === '200') {
          this.setState({
            data: result.data,
          });
          this.getCostKindName(result.data);
          let firstRenderBox = this.firstRenderBox(result.data);
          this.setState({
            firstRenderBox: firstRenderBox,
          });

        } else {
          Message.error(result.message, 10);
        }
      }
    });
  },
  // 初始化列表时获取所有消费项名称
  getCostKindName(data){
    let dataList = this.state.dataList;

    let params = this.state.params;
    data.map((item) =>{
      let obj ={
        key:'',
        costKindNid:'',
        costKindName:'',
        expenceMoney:'',
        price:'',
        num:'',
        remark:''
      };
      obj.costKindNid = item.nid;
      obj.costKindName = item.name;
      obj.key = this.key++;
      params.push(obj);
    })
    dataList.costList = params;
    this.setState({
      params:params,
      dataList: dataList
    })
  },
  // 获取输入框的值
  handleChange(e ,value){
    let name, id, val;

    if(e.target){// input
      name = e.target.name;
      id = e.target.id;
      val = e.target.value;
    }else{//  select
      id = e.id;
      name= e.name;
      val = Utils.formatDate(value);
    }


    let params = this.state.params;
    let dataList = this.state.dataList;

    let paramsId = parseInt(id.replace(/[^0-9]+/g, ''));
    let flag = false; // 不存在该条数据


    // 寻找已有数据params，查询是否存在key等于paramsId的记录
    params.map((item) =>{

      if(item.key ==  paramsId){
        flag = true;
        item[name] = val;
        // 当数量和价格有输入时，计算消费金额

        if((name== 'price'|| name== 'num') && item.num != '' && item.price != ''){
          if(parseInt(item.num) && parseFloat(item.price)){

            item.expenceMoney = parseInt(item.num)*parseFloat(item.price);
            document.getElementById(`expenceMoneyHard${paramsId}`).value = (item.expenceMoney).toFixed(2);

          }
        }
      }
    });

    if(flag == false){// 不存在该条数据，则在数组params中追加一条数据
      let obj ={
        key:'',
        costKindNid:'',
        costKindName:'',
        expenceMoney:'',
        price:'',
        num:'',
        remark:''
      };
      obj[name] = e.target.value;
      obj.key = paramsId;
      params.push(obj);
    }else{ // 存在该条数据，则替换已有内容

    }
    dataList.costList = params

    this.setState({
      params:params,
     // dataList: dataList
    })

    this.getDataList(dataList);

  },

  // 添加一行费用项
  addCost() {
    let keys = this.state.costArry;
    keys = keys.concat(this.uuid);
    this.setState({
      costArry: keys
    });
    let val = {
      costArry: keys,
    }
    let renderBox = this.costBox(keys);
    this.setState({
      renderBox: renderBox,
    });
    this.uuid++;
  },
  removeCost(k){
    let keys = this.state.costArry;
    let dataList = this.state.dataList;
    let costList = this.state.dataList.costList;
    let params = this.state.params;
    keys = keys.filter((key) => {
      return key !== k.k;
    });
    params = params.filter((key) => {
      return key.key !== k.k;
    });
    costList = costList.filter((key) => {
      return key.key !== k.k;
    });
    dataList.costList = costList; 
    
    this.setState({
      costArry: keys,
      params:params
    });

    let renderBox = this.costBox(keys);
    this.setState({
      renderBox: renderBox,
      dataList: dataList
    });
  },

  costBox(val){
    const formItems = val.map((k) => {
      let costKindName = `costKindName${k}`;
      let expenceMoney = `expenceMoneyHard${k}`;
      let expenceTime = `expenceTime${k}`;
      let num = `num${k}`;
      let price = `price${k}`;
      let remark = `remark${k}`;
      return (
        <Row gutter={16} key={k}>
          <Col className="gutter-row" span={3} offset={1} >
            <div className="gutter-box">
              <Input type="text" id={costKindName} name="costKindName" onChange={this.handleChange}/>
            </div>
          </Col>
          <Col className="gutter-row" span={3}>
            <div className="gutter-box">
              <Input type="text" id={num} name="num" onChange={this.handleChange}/>
            </div>
          </Col>
          <Col className="gutter-row" span={3}>
            <div className="gutter-box">
              <Input type="text" id={price} name="price" onChange={this.handleChange}/>
            </div>
          </Col>
          <Col className="gutter-row" span={3}>
            <div className="gutter-box">
              <Input disabled={true} id={expenceMoney} name="expenceMoney" />
            </div>
          </Col>
          <Col className="gutter-row" span={3}>
            <div className="gutter-box">
              <DatePicker id={expenceTime} name="expenceTime" onChange={this.handleChange.bind(this, {id:expenceTime, name:'expenceTime'})}/>
            </div>
          </Col>
          <Col className="gutter-row" span={3}>
            <div className="gutter-box">
              <Input type="textarea" id={remark} name="remark" style={{height:30}} onBlur={this.handleChange}  />
            </div>
          </Col>

          <Col className="gutter-row" span={3}>
            <div className="gutter-box">
              <Button type="ghost" onClick={this.removeCost.bind(this, {k})}><Icon type="delete"/>删除</Button>
            </div>
          </Col>
        </Row>
      );
    });
    return (
      <div>
        {formItems}
      </div>
    );
  },
  firstRenderBox(val){
    let data = this.state.data;
    const firstRender = val.map((item) => {
      let type = item.type;
      let nid = item.nid;
      let name = item.name;
      let uuid = this.uuid;
      let tenementId = `tenementId${uuid}`;
      let costKindNid = `costKindNid${uuid}`;
      let costKindName = `costKindName${uuid}`;
      let num = `num${uuid}`;
      let price = `price${uuid}`;
      let expenceMoney = `expenceMoneyHard${uuid}`;
      let expenceTime = `expenceTime${uuid}`;
      let remark = `remark${uuid}`;
      this.uuid++;
      return (
        <Row gutter={16} key={this.uuid}>
          <Col className="gutter-row" span={3} offset={1}>
            <div className="gutter-box">
              <Input type="hidden" id={costKindNid} value={nid} name="costKindName" value={nid}/>
              <Input type="hidden" id={costKindName} value={name} name="costKindName" value={name}/>
              <span>{name}</span>
            </div>
          </Col>
          <Col className="gutter-row" span={3}>
            <div className="gutter-box">
              <Input type="text" id={num}  name="num"  onChange={this.handleChange}/>
            </div>
          </Col>
          <Col className="gutter-row" span={3}>
            <div className="gutter-box">
              <Input type="text" id={price}  name="price"  onChange={this.handleChange}/>
            </div>
          </Col>
          <Col className="gutter-row" span={3}>
            <div className="gutter-box">
              <Input disabled={true} id={expenceMoney} name="expenceMoney" />
            </div>
          </Col>
          <Col className="gutter-row" span={3}>
            <div className="gutter-box">
              <DatePicker  id={expenceTime} name="expenceTime" onChange={this.handleChange.bind(this, {id:expenceTime, name:'expenceTime'})}/>
            </div>
          </Col>

          <Col className="gutter-row" span={3}>
            <div className="gutter-box">
              <Input type="textarea" id={remark} name="remark" style={{height:30}}  onChange={this.handleChange}/>
            </div>
          </Col>
          <Col className="gutter-row" span={3}>
            <div className="gutter-box">--</div>
          </Col>
        </Row>
      );
    });
    this.uuid = data.length;
    return (
      <div>
        {firstRender}
      </div>
    );

  },
  getDataList(){
    let dataList = this.state.dataList;
    let costList = [];
    if(dataList.costList){
      dataList.costList.map((item,key) =>{

        if(item.costKindName !==""  && item.num!=="" && item.price!==""){
          costList.push(item);
        }
      });
    }
    dataList.costList =  costList;

  },

  handleSubmit(e){

    this.setState({
      loading: true,
    });
    Utils.sendAjax({
      url: '/decorate/cost/add',
      data:JSON.stringify(this.state.dataList),
      callback:(result) => {
        if (result.code === '200') {
          Message.success(result.message);
          this.handleReturn();

        } else {
          this.setState({
            loading: false,
          });
          Message.error(result.message, 10);
        }
      }
    });
  },
  handleReturn(){
    let state = this.props.allProps;
    let goPathUrl = '/landlord/houseDecoration/list';
    this.context.router.push({pathname: goPathUrl, state: {...state}});
  },
  render () {
    return (
      <div>
        <div className="form-group">
          <h3><span>硬装项目</span></h3>
          <div>
            <div className="row-table" >
              <Row className="table-title" gutter={16}>
                <Col className="gutter-row" span={3} offset={1}>
                  <div className="gutter-box">费用项</div>
                </Col>
                <Col className="gutter-row" span={3}>
                  <div className="gutter-box">个数</div>
                </Col>
                <Col className="gutter-row" span={3}>
                  <div className="gutter-box">单价</div>
                </Col>
                <Col className="gutter-row" span={3}>
                  <div className="gutter-box">消费金额</div>
                </Col>
                <Col className="gutter-row" span={3}>
                  <div className="gutter-box">消费日期</div>
                </Col>
                <Col className="gutter-row" span={3}>
                  <div className="gutter-box">备注</div>
                </Col>
                <Col className="gutter-row" span={3}>
                  <div className="gutter-box">操作</div>
                </Col>
              </Row>
              <Form >

                {this.state.firstRenderBox}
                {this.state.renderBox}


                <Row gutter={16}>
                  <Col className="gutter-row" span={3} offset={1} >
                    <Button type="ghost" onClick={this.addCost} ><Icon type="plus" />新增</Button>
                  </Col>

                </Row>
                <Row gutter={16}>
                  <Col className="gutter-row" span={8}  offset={1} >
                    <Button type="primary" loading={this.state.loading} onClick={this.handleSubmit} >提交</Button>
                    <Button type="ghost" style={{marginLeft : 10}} onClick={this.handleReturn}>返回</Button>
                  </Col>
                </Row>
              </Form>
            </div>
          </div>
        </div>

      </div>
    );
  }
});

Demo = Form.create()(Demo);
export default Demo
